package xh;

import com.alibaba.fastjson.JSON;
import xh.protocol.DownLoadRequestHeader;
import xh.protocol.DownLoadResponseHeader;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created by dell-pc on 2016/7/6.
 */
public class DownLoadFile {

    Socket getServerConnect(String ip, int port) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(ip, port));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return socket;
    }

    void download(FileListManager.FileInfo fileInfo) {
        String fileId = fileInfo.fileId;
        int offset = 0;
        Socket socket = getServerConnect(fileInfo.remoteIps.first(), Global.FileServerPort);
        DataOutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;


        DownLoadRequestHeader h = new DownLoadRequestHeader();

        h.setFileId(fileId);
        h.setOffset(offset);

        String headJson = JSON.toJSONString(h);

        File tmpFile = null;
        File newName = null;
        try {

            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            byte[] bytes = headJson.getBytes("utf-8");
            dataOutputStream.writeInt(bytes.length);
            dataOutputStream.write(bytes);

            dataInputStream = new DataInputStream(socket.getInputStream());

            int RHlength = dataInputStream.readInt();

            bytes = new byte[RHlength];
            dataInputStream.read(bytes);

            DownLoadResponseHeader rh = JSON.parseObject(new String(bytes, "utf-8"), DownLoadResponseHeader.class);
            if (rh.getResultCode() == 0) {
                tmpFile = new File(Global.BasePath, Global.toDownloadingFileName(h.getFileId()));
                newName = new File(tmpFile.getParent(), rh.getFileName());

                DataOutputStream tfdos = new DataOutputStream(new FileOutputStream(tmpFile));
                int hasReadLength = 0;
                while (hasReadLength < rh.getFileBufLength()) {
                    byte[] buf = new byte[1024 * 1024];
                    int l = dataInputStream.read(buf);
                    if (l > 0) {
                        tfdos.write(buf, 0, l);
                        hasReadLength += l;
                    } else {
                        System.out.println("wriet ok");
                        break;
                    }
                }

                tfdos.close();
                tmpFile.renameTo(newName);

            } else {
                System.out.println(rh.getResultString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dataOutputStream.close();
            } catch (Exception e) {
            }

            try {
                dataInputStream.close();
            } catch (Exception e) {
            }
        }
    }

    public static void main(String[] args) {
//        new DownLoadFile().download("E:\\test\\test-server-file1", "aa", 1);
//        new DownLoadFile().download("E:\\test\\test.txt", "aa", 0);
//        new DownLoadFile().download("E:\\test\\firefox-cache-media.zip", "aa", 0);
    }
}


